const {
  Worker,
  isMainThread,
  parentPort,
  workerData,
} = require("worker_threads");

if (isMainThread) {
  function generatePrimesAsync(...arg) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: arg,
      });
      worker.on("message", resolve);
      worker.on("error", reject);
      worker.on("exit", (code) => {
        console.log(`Worker stopped with exit code ${code}`);
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  }
  module.exports = {
    generatePrimes: generatePrimesAsync,
  };
} else {
  const { generatePrimes } = require("./block_primes");
    console.log("---------->in analyzeDataAdvance child, param:", ...workerData);
  parentPort.postMessage(generatePrimes(...workerData));
}
